package game.phases.actionphase.commands 
{
	import game.map.Unit;
	import game.map.UnitTypes;
	import game.unitmanager.ArmyController;
	/**
	 * ...
	 * @author rnk
	 */
	public class LossesCalculator 
	{
		private var armies:Array;
		private var casualties:int;
		
		public function LossesCalculator(armies:Array,casualties:int) 
		{
			this.casualties = casualties;
			this.armies = armies;
			
		}
		
		
		public function GetResult():Object
		{
			var result:Object = { casualties:casualties,units:0,armiesDestroyed:0 ,unitsList:[]};
			
			//just dumb check
			if (casualties <= 0 || armies.length==0)
				return result;
			
			//collect all units in all armies in one list 
			var allUnits:Array = [];
			for each (var ac:ArmyController in armies) 
			{
				for each (var item:Unit in ac.model.units) 
				{
					allUnits.push( { controller:ac, unit:item } );
				}
			}
			
			//filter by cost
			FilterByCost(allUnits, casualties);
			
			
			//randomly kill units
			while (allUnits.length>0 && GetLowestUnitCost(allUnits) <= casualties && casualties > 0)
			{
				result.unitsList.push(KillRandomUnit(allUnits));
				result.units = result.unitsList.length;
				FilterByCost(allUnits, casualties);
			}
			
			//clean empty armies from controllers list
			for each (ac in armies) 
			{
				ac.view.Refresh();
				if (ac.model.units.length == 0)
				{
					ac.Kill();
					result.armiesDestroyed++;
				}
			}
			
			//send word that armies been destroyed
			
			return result;
		}
		
		private function FilterByCost(allUnits:Array, casualties:int):Array 
		{
			for (var i:int = allUnits.length-1; i >=0 ; i--)
			{
				if (UnitTypes.UNIT_PARAMS[allUnits[i].unit.type].hp > casualties)
					allUnits.splice(i, 1);
				
			}
			return allUnits;
		}
		
		private function GetLowestUnitCost(allUnits:Array):int 
		{
			if (allUnits.length == 0) return 0;
			var min:int = UnitTypes.UNIT_PARAMS[allUnits[0].unit.type].hp
			for each (var item:Object in allUnits) 
			{
				if (UnitTypes.UNIT_PARAMS[item.unit.type].hp < min)
					min = UnitTypes.UNIT_PARAMS[item.unit.type].hp;
			}
			return min;
		}
		
		private function KillRandomUnit(allUnits:Array):Object 
		{
			if (allUnits.length == 0) return null;
			var result:Object= {};
			var rdx:int = Math.floor(Math.random() * allUnits.length);
			var unit:Unit = allUnits[rdx].unit;
			
			result.unit = unit.type;
			result.player = (allUnits[rdx].controller as ArmyController).loyalty;
			
			casualties -= UnitTypes.UNIT_PARAMS[unit.type].hp;
			
			(allUnits[rdx].controller as ArmyController).RemoveUnit(unit);
			
			allUnits.splice(rdx,1);
			
			return result;
		}
		
	}

}